import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', () => {
    const user = ref(null)
    const token = ref(localStorage.getItem('token') || '')
    const isLoggedIn = computed(() => !!token.value)

    // 存储注册用户数据
    const registeredUsers = ref(JSON.parse(localStorage.getItem('registeredUsers') || '[]'))

    // 登录
    function login(loginData) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                // 检查是否已注册
                const foundUser = registeredUsers.value.find(
                    u => u.username === loginData.username && u.password === loginData.password
                )

                if (foundUser) {
                    const userData = {
                        id: foundUser.id,
                        username: foundUser.username,
                        name: foundUser.username,
                        phone: foundUser.phone,
                        email: foundUser.email,
                        role: 'user'
                    }
                    const authToken = 'jwt_token_' + Date.now()

                    user.value = userData
                    token.value = authToken

                    // 保存到localStorage
                    localStorage.setItem('token', authToken)
                    localStorage.setItem('user', JSON.stringify(userData))

                    resolve({ user: userData, token: authToken })
                } else {
                    reject(new Error('用户名或密码错误'))
                }
            }, 1000)
        })
    }

    // 注册
    function register(registerData) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                // 检查用户名是否已存在
                const userExists = registeredUsers.value.some(
                    u => u.username === registerData.username
                )

                if (userExists) {
                    reject(new Error('用户名已存在'))
                    return
                }

                if (registerData.username && registerData.password && registerData.confirmPassword) {
                    if (registerData.password !== registerData.confirmPassword) {
                        reject(new Error('两次输入密码不一致'))
                        return
                    }

                    const newUser = {
                        id: Date.now(),
                        username: registerData.username,
                        password: registerData.password,
                        phone: registerData.phone || '',
                        email: registerData.email || '',
                        createTime: new Date().toISOString()
                    }

                    // 添加到注册用户列表
                    registeredUsers.value.push(newUser)
                    localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers.value))

                    resolve({
                        message: '注册成功',
                        user: {
                            id: newUser.id,
                            username: newUser.username,
                            phone: newUser.phone,
                            email: newUser.email
                        }
                    })
                } else {
                    reject(new Error('注册信息不完整'))
                }
            }, 1000)
        })
    }

    // 登出
    function logout() {
        user.value = null
        token.value = ''
        localStorage.removeItem('token')
        localStorage.removeItem('user')
    }

    // 初始化认证状态
    function initAuth() {
        const savedToken = localStorage.getItem('token')
        const savedUser = localStorage.getItem('user')

        if (savedToken && savedUser) {
            token.value = savedToken
            user.value = JSON.parse(savedUser)
        }
    }

    return {
        user,
        token,
        isLoggedIn,
        registeredUsers,
        login,
        register,
        logout,
        initAuth
    }
})